package com.iwe3.protal.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Autowired
    private Environment environment;

    @Bean
    public RedisConnectionFactory lettuceConnectionFactory() {
        // 配置 Redis 服务器地址和端口
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(
                environment.getProperty("spring.data.redis.host"),
                Integer.valueOf(environment.getProperty("spring.data.redis.port")));
        // 如果需要密码认证
        config.setPassword(environment.getProperty("spring.data.redis.password"));
        LettuceConnectionFactory factory = new LettuceConnectionFactory(config);

        return factory;
    }


    //@Bean == @Controller  @Service  @Repository  @Component
    @Bean //<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
    public RedisTemplate<String,Object> redisTemplate(){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        //设置连接工厂
        redisTemplate.setConnectionFactory(lettuceConnectionFactory());
        //以下5行代码，解决：SpringBoot3.5.5 Redis无法反序列化：Java8的时间
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule()); //关键：注册 Java 8 时间模块
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 日期格式化为 ISO-8601 字符串
        // 配置序列化器
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(objectMapper, Object.class);
        redisTemplate.setDefaultSerializer(serializer);
        //此处：需要配置KEY & Value的序列化规则
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setHashValueSerializer(serializer);

        return redisTemplate;
    }
}
